package com.eurasia.assignment.infrastructure.client.hoj.resources;

import java.io.IOException;

import org.slf4j.LoggerFactory;

import feign.Logger;
import feign.Request;
import feign.Response;
import feign.Util;
import static feign.Util.decodeOrDefault;

/**
 * 自定义的Feign客户端日志记录器
 * 提供比标准Logger更详细的HTTP请求/响应记录
 */
public class HOJResourceClientLogger extends Logger {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(HOJResourceFeignClient.class);

    @Override
    protected void log(String configKey, String format, Object... args) {
        // 使用SLF4J记录日志
        if (logger.isDebugEnabled()) {
            logger.debug(String.format(methodTag(configKey) + format, args));
        }
    }

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {
        if (logger.isDebugEnabled()) {
            super.logRequest(configKey, logLevel, request);
            
            // 记录额外的请求细节
            if (logLevel.ordinal() >= Level.HEADERS.ordinal()) {
                logger.debug("[HOJ-CLIENT] Request Headers: {}", request.headers());
            }
            
            // 记录请求体
            if (logLevel.ordinal() >= Level.FULL.ordinal() && request.body() != null) {
                String bodyText = request.charset() != null 
                    ? new String(request.body(), request.charset()) 
                    : "Binary data";
                logger.debug("[HOJ-CLIENT] Request Body: {}", bodyText);
            }
        }
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {
        if (logger.isDebugEnabled()) {
            // 记录基本响应信息
            int status = response.status();
            logger.debug("[HOJ-CLIENT] Response Status: {} ({}ms)", status, elapsedTime);
            
            // 记录响应头
            if (logLevel.ordinal() >= Level.HEADERS.ordinal()) {
                logger.debug("[HOJ-CLIENT] Response Headers: {}", response.headers());
            }
            
            // 记录响应体
            if (logLevel.ordinal() >= Level.FULL.ordinal() && response.body() != null) {
                byte[] bodyData = Util.toByteArray(response.body().asInputStream());
                String bodyText = decodeOrDefault(bodyData, Util.UTF_8, "Binary data");
                logger.debug("[HOJ-CLIENT] Response Body: {}", bodyText);
                return response.toBuilder().body(bodyData).build();
            }
        }
        
        return response;
    }
} 